<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档上传 - AI教育助手</title>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --light-bg: #f8f9fa;
            --dark-text: #333;
            --light-text: #fff;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--dark-text);
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            box-shadow: var(--shadow);
        }
        
        .header h1 {
            color: var(--secondary-color);
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            padding: 30px;
            box-shadow: var(--shadow);
        }
        
        .upload-section {
            margin-bottom: 30px;
        }
        
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background-color: #fafafa;
        }
        
        .upload-area:hover {
            border-color: var(--primary-color);
            background-color: #f0f8ff;
        }
        
        .upload-area.dragover {
            border-color: var(--primary-color);
            background-color: #e1f0fa;
        }
        
        .upload-icon {
            font-size: 48px;
            color: #ccc;
            margin-bottom: 15px;
        }
        
        .file-input {
            display: none;
        }
        
        .file-info {
            margin-top: 20px;
            padding: 15px;
            background-color: #f0f8ff;
            border-radius: 8px;
            display: none;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
            margin: 10px 5px;
        }
        
        .btn:hover {
            background-color: #2980b9;
        }
        
        .btn:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        
        .btn-success {
            background-color: var(--success-color);
        }
        
        .btn-success:hover {
            background-color: #27ae60;
        }
        
        .btn-warning {
            background-color: var(--warning-color);
        }
        
        .btn-warning:hover {
            background-color: #e67e22;
        }
        
        .progress-container {
            margin-top: 20px;
            display: none;
        }
        
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #ecf0f1;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background-color: var(--primary-color);
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .status-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            display: none;
        }
        
        .status-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .document-list {
            margin-top: 30px;
        }
        
        .document-item {
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 10px;
            background-color: #fff;
        }
        
        .document-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .document-title {
            font-weight: bold;
            font-size: 18px;
        }
        
        .document-status {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-processing {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-completed {
            background-color: #d4edda;
            color: #155724;
        }
        
        .nav-links {
            text-align: center;
            margin-top: 20px;
        }
        
        .nav-links a {
            color: var(--primary-color);
            text-decoration: none;
            margin: 0 10px;
        }
        
        .nav-links a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>AI教育助手</h1>
        <p>文档上传与处理系统</p>
    </div>
    
    <div class="container">
        <div class="upload-section">
            <h2>上传文档</h2>
            <p>选择文档文件上传并处理，系统将自动将其存储到向量数据库中</p>
            
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">📁</div>
                <p>点击选择文件或拖拽文件到此处</p>
                <p class="small">支持 .txt 和 .pdf 文件</p>
                <input type="file" class="file-input" id="fileInput" accept=".txt,.pdf">
            </div>
            
            <div class="file-info" id="fileInfo">
                <p>已选择文件: <span id="fileName"></span></p>
                <p>文件大小: <span id="fileSize"></span></p>
                <button class="btn" id="processBtn">处理文档</button>
            </div>
        </div>
        
        <div class="progress-container" id="progressContainer">
            <h3>处理进度</h3>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            <p id="progressText">正在准备处理...</p>
        </div>
        
        <div class="status-message" id="statusMessage"></div>
        
        <div class="document-list" id="documentList">
            <h3>已处理文档</h3>
            <div id="documentsContainer">
                <!-- 文档列表将在这里显示 -->
                <p>暂无已处理的文档</p>
            </div>
        </div>
        
            <a href="../" class="back-link">← 返回主页</a>
    </div>

    <script>
        // 获取DOM元素
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const processBtn = document.getElementById('processBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');
        const statusMessage = document.getElementById('statusMessage');
        const documentsContainer = document.getElementById('documentsContainer');
        
        // 事件监听器
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                handleFileSelect(e.dataTransfer.files[0]);
            }
        });
        
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileSelect(e.target.files[0]);
            }
        });
        
        processBtn.addEventListener('click', processDocument);
        
        // 处理文件选择
        function handleFileSelect(file) {
            // 检查文件类型
            const validTypes = ['text/plain', 'application/pdf'];
            const fileExtension = file.name.split('.').pop().toLowerCase();
            const isValidType = validTypes.includes(file.type) || 
                               (fileExtension === 'txt') || 
                               (fileExtension === 'pdf');
            
            if (!isValidType) {
                showStatus('仅支持 .txt 和 .pdf 文件', 'error');
                return;
            }
            
            // 显示文件信息
            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            fileInfo.style.display = 'block';
            
            // 保存当前文件引用
            window.currentFile = file;
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 处理文档
        async function processDocument() {
            if (!window.currentFile) {
                showStatus('请先选择一个文件', 'error');
                return;
            }
            
            // 禁用按钮
            processBtn.disabled = true;
            processBtn.textContent = '处理中...';
            
            // 显示进度条
            progressContainer.style.display = 'block';
            updateProgress(0, '开始处理文档...');
            
            try {
                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', window.currentFile);
                
                // 发送文件到服务器
                const response = await fetch('/api/upload_document', {
                    method: 'POST',
                    body: formData
                });
                
                if (response.ok) {
                    const result = await response.json();
                    updateProgress(100, '文档处理完成');
                    showStatus(`文档 "${window.currentFile.name}" 处理成功！`, 'success');
                    loadDocumentList(); // 刷新文档列表
                } else {
                    throw new Error(`处理失败: ${response.statusText}`);
                }
            } catch (error) {
                console.error('处理文档时出错:', error);
                updateProgress(0, '处理失败');
                showStatus(`处理文档时出错: ${error.message}`, 'error');
            } finally {
                // 恢复按钮状态
                processBtn.disabled = false;
                processBtn.textContent = '处理文档';
            }
        }
        
        // 更新进度条
        function updateProgress(percent, text) {
            progressFill.style.width = percent + '%';
            progressText.textContent = text;
        }
        
        // 显示状态消息
        function showStatus(message, type) {
            statusMessage.textContent = message;
            statusMessage.className = 'status-message';
            statusMessage.classList.add(type === 'success' ? 'status-success' : 'status-error');
            statusMessage.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                statusMessage.style.display = 'none';
            }, 3000);
        }
        
        // 加载文档列表
        async function loadDocumentList() {
            try {
                // 这里应该调用API获取已处理的文档列表
                // 暂时显示模拟数据
                documentsContainer.innerHTML = `
                    <div class="document-item">
                        <div class="document-header">
                            <span class="document-title">示例文档.txt</span>
                            <span class="document-status status-completed">已完成</span>
                        </div>
                        <p>已处理并存储到向量数据库中</p>
                    </div>
                `;
            } catch (error) {
                console.error('加载文档列表时出错:', error);
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadDocumentList();
        });
    </script>
</body>
</html>